import { useState } from 'react'

function ModelGenerator({ onGenerate, onUpload, onClose }) {
    const [name, setName] = useState('')
    const [description, setDescription] = useState('')
    const [prompt, setPrompt] = useState('')
    const [imageFile, setImageFile] = useState(null)
    const [modelFile, setModelFile] = useState(null)
    const [mode, setMode] = useState('text') // 'text', 'image', or 'upload'

    const handleSubmit = (e) => {
        e.preventDefault()

        if (!name.trim()) {
            alert('请输入模型名称')
            return
        }

        if (mode === 'upload') {
            // 手动上传模型
            if (!modelFile) {
                alert('请选择模型文件')
                return
            }
            const formData = new FormData()
            formData.append('name', name)
            formData.append('description', description)
            formData.append('file', modelFile)
            onUpload(formData)
            onClose()
            return
        }

        const data = { name, description }

        if (mode === 'text') {
            if (!prompt.trim()) {
                alert('请输入文本描述')
                return
            }
            data.prompt = prompt
        } else if (mode === 'image') {
            if (!imageFile) {
                alert('请上传图片')
                return
            }
            // 转换为 base64
            const reader = new FileReader()
            reader.onload = () => {
                data.image_base64 = reader.result.split(',')[1]
                onGenerate(data)
            }
            reader.readAsDataURL(imageFile)
            return
        }

        onGenerate(data)
    }

    return (
        <div className="fixed inset-0 bg-black/70 backdrop-blur-sm flex items-center justify-center z-50 p-4" onClick={onClose}>
            <div className="bg-dark-800 border border-dark-700 rounded-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto shadow-2xl" onClick={(e) => e.stopPropagation()}>
                <div className="p-6">
                    <h2 className="text-2xl font-semibold mb-6 text-gray-100">✨ 生成 3D 模型</h2>

                    {/* Mode Selector */}
                    <div className="grid grid-cols-3 gap-3 mb-6">
                        <button
                            type="button"
                            className={`py-3 px-4 rounded-lg font-medium transition-all duration-200 ${mode === 'text'
                                    ? 'bg-blue-600 text-white shadow-lg shadow-blue-600/30'
                                    : 'bg-dark-700 text-gray-400 hover:bg-dark-600 hover:text-gray-300'
                                }`}
                            onClick={() => setMode('text')}
                        >
                            📝 文本生成
                        </button>
                        <button
                            type="button"
                            className={`py-3 px-4 rounded-lg font-medium transition-all duration-200 ${mode === 'image'
                                    ? 'bg-blue-600 text-white shadow-lg shadow-blue-600/30'
                                    : 'bg-dark-700 text-gray-400 hover:bg-dark-600 hover:text-gray-300'
                                }`}
                            onClick={() => setMode('image')}
                        >
                            🖼️ 图片生成
                        </button>
                        <button
                            type="button"
                            className={`py-3 px-4 rounded-lg font-medium transition-all duration-200 ${mode === 'upload'
                                    ? 'bg-blue-600 text-white shadow-lg shadow-blue-600/30'
                                    : 'bg-dark-700 text-gray-400 hover:bg-dark-600 hover:text-gray-300'
                                }`}
                            onClick={() => setMode('upload')}
                        >
                            📤 上传模型
                        </button>
                    </div>

                    <form onSubmit={handleSubmit} className="space-y-4">
                        <div>
                            <input
                                type="text"
                                placeholder="模型名称"
                                value={name}
                                onChange={(e) => setName(e.target.value)}
                                className="input-field"
                                required
                            />
                        </div>

                        <div>
                            <textarea
                                placeholder="模型描述（可选）"
                                value={description}
                                onChange={(e) => setDescription(e.target.value)}
                                rows="3"
                                className="input-field resize-none"
                            />
                        </div>

                        {mode === 'text' && (
                            <div>
                                <textarea
                                    placeholder="描述你想要的 3D 模型，例如：一只可爱的卡通猫"
                                    value={prompt}
                                    onChange={(e) => setPrompt(e.target.value)}
                                    rows="4"
                                    className="input-field resize-none"
                                    required
                                />
                            </div>
                        )}

                        {mode === 'image' && (
                            <div className="card bg-dark-700 border-dark-600">
                                <p className="text-gray-300 mb-3">上传参考图片</p>
                                <input
                                    type="file"
                                    accept="image/*"
                                    onChange={(e) => setImageFile(e.target.files[0])}
                                    className="block w-full text-sm text-gray-400
                                        file:mr-4 file:py-2 file:px-4
                                        file:rounded-lg file:border-0
                                        file:text-sm file:font-medium
                                        file:bg-blue-600 file:text-white
                                        hover:file:bg-blue-700
                                        file:cursor-pointer file:transition-colors"
                                    required
                                />
                                {imageFile && (
                                    <p className="mt-2 text-sm text-blue-400">✓ 已选择：{imageFile.name}</p>
                                )}
                            </div>
                        )}

                        {mode === 'upload' && (
                            <div className="card bg-dark-700 border-dark-600">
                                <p className="text-gray-300 mb-3">上传 .glb 格式的 3D 模型文件</p>
                                <input
                                    type="file"
                                    accept=".glb,model/gltf-binary"
                                    onChange={(e) => setModelFile(e.target.files[0])}
                                    className="block w-full text-sm text-gray-400
                                        file:mr-4 file:py-2 file:px-4
                                        file:rounded-lg file:border-0
                                        file:text-sm file:font-medium
                                        file:bg-blue-600 file:text-white
                                        hover:file:bg-blue-700
                                        file:cursor-pointer file:transition-colors"
                                    required
                                />
                                {modelFile && (
                                    <p className="mt-2 text-sm text-blue-400">✓ 已选择：{modelFile.name}</p>
                                )}
                            </div>
                        )}

                        <div className="flex gap-3 pt-4">
                            <button type="button" onClick={onClose} className="btn-secondary flex-1">
                                取消
                            </button>
                            <button type="submit" className="btn-primary flex-1">
                                {mode === 'upload' ? '上传' : '开始生成'}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    )
}

export default ModelGenerator
